package com.suian.spring.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Component
public class RedisDistributedLock {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 锁键前缀
    private static final String LOCK_PREFIX = "LOCK:";
    // 锁默认过期时间（毫秒）
    private static final long DEFAULT_EXPIRE = 30000;

    /**
     * 尝试获取分布式锁
     * @param lockKey   锁的键名
     * @param requestId 请求标识（确保锁的持有者才能释放）
     * @param expire    锁的过期时间（毫秒）
     * @return 是否获取成功
     */
    public boolean tryLock(String lockKey, String requestId, long expire) {
        String key = LOCK_PREFIX + lockKey;
        return Boolean.TRUE.equals(
                redisTemplate.opsForValue().setIfAbsent(
                        key,
                        requestId,
                        expire,
                        TimeUnit.MILLISECONDS
                )
        );
    }

    /**
     * 释放分布式锁（Lua脚本保证原子性）
     * @param lockKey   锁的键名
     * @param requestId 请求标识
     * @return 是否释放成功
     */
    public boolean releaseLock(String lockKey, String requestId) {
        String key = LOCK_PREFIX + lockKey;
        String script =
                "if redis.call('get', KEYS[1]) == ARGV[1] then " +
                        "   return redis.call('del', KEYS[1]) " +
                        "else " +
                        "   return 0 " +
                        "end";
        Long result = redisTemplate.execute(
                new DefaultRedisScript<>(script, Long.class),
                Collections.singletonList(key),
                requestId
        );
        return result != null && result == 1;
    }
    /**
     * 获取锁（简化版，使用默认过期时间）
     */
    public boolean tryLock(String lockKey, String requestId) {
        return tryLock(lockKey, requestId, DEFAULT_EXPIRE);
    }
}
